﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmailTemplate.aspx.cs" Inherits="CRMWeb.Pages.Admin.EmailTemplate" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>EMail Template</title>
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <link rel="stylesheet" id="newtheme" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/Scripts/common.js"></script>
    <script src="../../tiny_mce/tiny_mce.js"></script>
</head>
<body>
    <div class="easyui-panel" title="Email Template" id="pnlMain" style="width: auto; height: auto">

        <div style="float: left; width: 300px">
            <div id="pnltree" class="easyui-panel" title="E-Mail Category">
                <ul id="tvEmailCategory" class="easyui-tree" animate="true" data-options="url:'/WebServices/EmailTemplate.ashx?method=DisplayCategoryList&Company=' + getQuerystring('Company', ''),required:true,
                    onSelect:function(node){
                       $('#dgList').datagrid({
                        url: '/WebServices/EmailTemplate.ashx?method=GetEmailDataList&Company=' + getQuerystring('Company', '')+'&CategoryId='+node.id
                        });
                    },
                    onLoadSuccess:function(){
                     var rootnode = $('#tvEmailCategory').tree('getRoot');
                            if (rootnode == null) {
                                $('#divEmailTemplate').hide();
                                $.messager.alert('Morgan CRM', 'No Email Template available ' + usrCompany, 'info');
                            }
                            else {
                                $('#divEmailTemplate').show();
                                $('#tvEmailCategory').tree('select', rootnode.target);
                            }
                            $('#dgList').datagrid('resize', {
                            width: window.innerWidth - 310,
                            height: window.innerHeight - 30
                            }); 
                    }">
                </ul>
            </div>
        </div>
        <div id="divEmailTemplate" style="width: 450px">
            <table id="dgList" style="width: auto; height: 640px;"
                toolbar="#toolbarList" pagination="true" data-options="pageSize:20"
                rownumbers="true" fitcolumns="true" singleselect="true" autorowheight="true">
                <thead>
                    <tr>
                        <th field="EmailTemplate" width="100" align="center">TemplateName</th>
                        <th field="EmailCompany" width="80" align="center">Company</th>
                        <th field="emailSubject" width="100" align="center">Subject</th>
                    </tr>
                </thead>
            </table>
            <div id="toolbarList">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="newEmailemplate()">New</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-edit" plain="true" onclick="editEmailTemplate()">Edit</a>
                <a id="lnkDelete" href="javascript:void(0)" class="easyui-linkbutton" onclick="openDelEmailPopup()" plain="true" iconcls="icon-remove" title="Delete Notice">Delete</a>
            </div>
        </div>
    </div>





    <div id="dlgETem" class="easyui-dialog" style="width: 600px; height: 650px; padding: -3px"
        closed="true" buttons="#dlg-buttons">
        <form id="fmETemp" method="post" novalidate>
            <div class="fitem" style="margin-top: 9px;">
                <label style="width: 120px; margin-left: 20px">Select Template:</label>
                <span id="spnddlEmailTemplate">

                    <input class="easyui-combotree" value="" id="ddlEMAILTemplate" style="width: 300px;"
                        data-options="url:'/WebServices/EmailTemplate.ashx?method=DisplayTemplateNode&Company=' + getQuerystring('Company', ''),
                        id: 'EmailId',
		                text: 'EmailTemplate',required:true, onSelect:selectEmailTemplate " />
                </span>


                <input id="txtEmailTemplate" class="easyui-validatebox" required="true" hidden="true" />
            </div>


            <div class="fitem">
                <label style="width: 120px; margin-left: 20px">Company:</label>
                <input class="easyui-combobox" id="cmbEmailRoles" style="width: 300px;"
                    data-options="panelWidth:300, 
                             editable:false,
                     multiple:true,
                        valueField: 'MemberGroupName',  
                        textField: 'MemberGroupName',
                        url: '/WebServices/Notice.ashx?method=BindAllRole',
                    selected:true" />
            </div>


            <div class="fitem">
                <label style="width: 120px; margin-left: 20px">Field:</label>
                <input class="easyui-combobox" id="cmbadmin_field" name="admin_field" style="width: 300px;" data-options="panelHeight:'300',url:'/WebServices/EmailTemplate.ashx?method=getColumnName',
				valueField:'COLUMN_NAME',
				textField:'COLUMN_NAME',
                  onSelect: function(rec){  
                    var caretPos = document.getElementById('txtTemplate').selectionStart;
                    var textAreaTxt = jQuery('#txtTemplate').val();
                    var txtToAdd = '%'+rec.COLUMN_NAME+'%';
                    tinyMCE.execInstanceCommand('txtTemplate','mceInsertContent',false,txtToAdd);
                }" />
            </div>
            <div class="fitem">
                <span id="spnCategory" style="display: none">
                    <label style="width: 120px; margin-left: 20px">Category:</label>
                    <select class="easyui-combotree" id="cmbCategory" style="width: 300px;"
                        data-options="url:'/WebServices/EmailTemplate.ashx?method=DisplayCategoryList&Company=' + getQuerystring('Company', ''),
                        required:true">
                    </select>

                </span>
            </div>
            <div class="fitem">
                <label style="width: 120px; margin-left: 20px">Operator:</label>
                <select id="cmbOperator" class="easyui-combobox" name="Operator" style="width: 110px;" data-options="panelHeight:'auto',
                    onSelect: function(rec){
                    var getVal=$('#cmbOperator').combogrid('getValue');
                    tinyMCE.execInstanceCommand('txtTemplate','mceInsertContent',false,getVal);
                    }">
                    <option value="%OperatorName%">Operator Name</option>
                </select>
                <input id="txtOpr" class="easyui-validatebox" required="true" hidden="true" />
            </div>
            <div class="fitem">
                <label style="width: 120px; margin-left: 20px">Subject:</label>
                <input type="text" id="txtEmailSub" aria-multiline="true" required="required" style="width: 298px" />
            </div>
            <div class="fitem">
                <label style="width: 120px; margin-left: 20px">Description:</label>
            </div>
            <div data-options="region:'center'" style="padding: 10px; height: 80%" class="emailbox">
                <textarea id="txtTemplate" name="Template" class="easyui-validatebox" style="width: 100%; height: 550px"></textarea>
            </div>

            <input type="hidden" id="hdnEmailRole" runat="server" />
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#dlgETem').dialog('close')" style="float: left">Cancel</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="SaveEmailTemplates()">Save</a>
    </div>
    <div id="dlgDelList" class="easyui-dialog" title="Confirm" style="width: 300px; height: 160px" closed="true" resizable="false" modal="true">
        <h4 style="text-align: center">Are you sure want to delete this template?</h4>
        <div class="fitem" style="text-align: center; padding: 10px; margin-top: 10px">
            <a id="lnkDelList" href="javascript:void(0)" class="easyui-linkbutton" onclick="deleteEmailTemplate()" disabled="true">OK</a>
            <a id="lnkCancleList" href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgDelList').dialog('close')" disabled="true">Cancel</a>
            <span id="spnanimate">
                <img id="deleteProgress" style="margin-left: 20px" src="../../Media/loading.gif" />
                <label id="lbltimeOutn" style="margin-left: 20px">5</label>
            </span>
        </div>
    </div>
</body>
<script type="text/javascript">

    //Change Theme:
    function getQuerystring(key, defaultValue) {
        if (defaultValue == null) defaultValue = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return defaultValue;
        else {
            return qs[1];
        }
    }


    $(document).ready(function () {
        $('#newtheme').attr('href', '/EasyUI/Themes/' + getQuerystring('Theme', '') + '/easyui.css');

    });

    $('#dlgDelList').dialog({
        onOpen: function () {

            startCounter(5);

        },
        onClose: function () {
            $('#lnkDelList').linkbutton('disable');
            $('#lnkCancleList').linkbutton('disable');
            $('#spnanimate').show();
            $('#lbltimeOutn').html('');
        }
    });



    function startCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#lnkDelList').linkbutton('enable');
                $('#lnkCancleList').linkbutton('enable');
                $('#spnanimate').hide();

            }
            else {
                $('#lbltimeOutn').html(limit);
                startCounter(limit - 1);
            }
        }, 1000);
    }



    var CurrentEmailRole = '';
    var setEmailRoles = '';
    tinyMCE.init({
        mode: "exact",
        elements: "txtTemplate",
        theme: "advanced",
        plugins: "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,help,code,|,forecolor,backcolor",
        setup: function (ed) {
            ed.onInit.add(function (ed) {
                ed.getDoc().body.style.fontSize = '13pt';
            });
        }
    });


    $(document).ready(function () {
        $('#ddlEMAILTemplate').combotree({
            onClick: function (node) {
                if (!$('#ddlEMAILTemplate').tree('isLeaf', node.target)) {
                    $('#ddlEMAILTemplate').combotree('setValues', '');
                    var t = $('#ddlEMAILTemplate').combotree('tree');
                    t.tree('toggle', node.target);
                    var p = $('#ddlEMAILTemplate').combotree('panel');
                    p.panel('open');
                }
            }
        });
        $('#cmbCategory').combotree({
            onClick: function (node) {
                if (!$('#cmbCategory').tree('isLeaf', node.target)) {
                    $('#cmbCategory').combotree('setValues', '');
                    var t = $('#cmbCategory').combotree('tree');
                    t.tree('toggle', node.target);
                    var p = $('#cmbCategory').combotree('panel');
                    p.panel('open');
                }
            }
        });

        $('#pnltree').panel('resize', {
            height: window.innerHeight - 30
        });

        $('#ddlEMAILTemplate').combobox('textbox').bind('click', function () {
            $('#ddlEMAILTemplate').combobox('showPanel');
        });
        $('#cmbEmailRoles').combobox('textbox').bind('click', function () {
            $('#cmbEmailRoles').combobox('showPanel');
        });

        $('#cmbadmin_field').combobox('textbox').bind('click', function () {
            $('#cmbadmin_field').combobox('showPanel');
        });
        $('#cmbCategory').combobox('textbox').bind('click', function () {
            $('#cmbCategory').combobox('showPanel');
        });
        $('#cmbOperator').combobox('textbox').bind('click', function () {
            $('#cmbOperator').combobox('showPanel');
        });
        $('#lnkCancleEmailTemp').hide();
        $('#lnkDeleteEmailTemp').hide();

    });
    function newEmailemplate() {
        $('#dlgETem').dialog('open');
        $('#dlgETem').panel('setTitle', 'Create New E-Mail Template');
        $('#txtEmailTemplate').val('');
        $('#ddlEMAILTemplate').combotree('reload');
        $('#cmbCategory').combotree('reload');

        $('#ddlEMAILTemplate').combotree('setValue', '');
        $('#cmbEmailRoles').combobox({
            onLoadSuccess: function (data) {
                $(this).combobox('select', data[0]['MemberGroupName']);
            },
        });
        $('#cmbadmin_field').combobox('setValue', '');
        $('#txtEmailTemplate').show();
        $('#txtEmailSub').val('');
        $('#spnddlEmailTemplate').hide();
        $('#spnCategory').show();
        $('#lnkDeleteEmailTemp').hide();
        $('#lnkCancleEmailTemp').show();
        $('#lnkNewEmailTemp').hide();
        tinymce.get('txtTemplate').setContent('');
    }




    function cancelEmailTemplate() {

        $('#dlgETem').panel('setTitle', 'E-Mail Template');
        $('#dgList').datagrid('reload');
        $('#dlgETem').dialog('close');
        $('#txtEmailTemplate').val('');
        $('#spnCategory').hide();
        $('#ddlEMAILTemplate').combotree('reload');
        $('#cmbCategory').combotree('setValue', '');
        $('#ddlEMAILTemplate').combotree('setValue', '');
        $('#cmbadmin_field').combobox('setValue', '');
        $('#cmbEmailRoles').combobox('setValues', '');
        $('#txtEmailSub').val('');
        $('#txtEmailTemplate').hide();
        $('#spnddlEmailTemplate').show();
        $('#lnkDeleteEmailTemp').hide();
        $('#lnkCancleEmailTemp').hide();
        $('#lnkNewEmailTemp').show();
        tinymce.get('txtTemplate').setContent('');

    }
    $(document).keydown(function (event) {
        if ((event.which == 83 || event.which == 115) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            SaveEmailTemplates();
            return false;
        }
        return true;
    });

    function IsValidate() {


        var flag = true;
        if ($('#txtEmailTemplate').is(':visible') == true && $('#txtEmailTemplate').val() == '') {
            $.messager.alert('Morgan CRM', 'Template name is required.', 'warning');
            return flag = false;
        }

        var trCat = $('#cmbCategory').combotree('tree');	// get the tree object
        var CategorynodeTr = trCat.tree('getSelected');

        if (CategorynodeTr == null) {
            $.messager.alert('Morgan CRM', 'Please select category... !', 'warning');
            return flag = false;
        }

        if ($('#txtEmailSub').val() == '') {
            $.messager.alert('Morgan CRM', 'Subject is required.', 'warning');
            return flag = false;
        }
        return flag;
    }


    //Save & update email template:
    function SaveEmailTemplates() {
        if (IsValidate()) {
            var EmailId = '';
            var tr = $('#cmbCategory').combotree('tree');	// get the tree object
            var Categorynode = tr.tree('getSelected');            // get selected node

            var t = $('#ddlEMAILTemplate').combotree('tree');	// get the tree object
            var templatNode = t.tree('getSelected');

            if (templatNode != null)
                EmailId = templatNode.id;

            var EmailTemplate = $('#txtEmailTemplate').val();
            var EmailTemplateFormat = encodeURIComponent(tinyMCE.get('txtTemplate').getContent());
            var EmailCompany = $('#cmbEmailRoles').combobox('getText');
            var emailSubject = $('#txtEmailSub').val();




            if (EmailId != '') {
                $.ajax({
                    url: '/WebServices/EmailTemplate.ashx',
                    type: 'POST',
                    data: {
                        method: 'EmailTemplateUpdate',
                        args: { EmailId: EmailId, TemplateFormat: EmailTemplateFormat, emailSubject: emailSubject, CategoryID: Categorynode.id, EmailCompany: EmailCompany },
                    },
                    success: function (data) {
                        if (data == 1) {
                            $.messager.alert('Morgan CRM', 'Email template updated successfully.');
                            cancelEmailTemplate();
                        }
                        else {
                            $.messager.alert('Morgan CRM', 'Email template already exist.');
                        }
                    }
                });

            }
            else {
                if (EmailTemplate != '') {
                    $.ajax({
                        url: '/WebServices/EmailTemplate.ashx',
                        type: 'POST',
                        data: {
                            method: 'EmailTemplateAdd',
                            args: { EmailTemplate: EmailTemplate, TemplateFormat: EmailTemplateFormat, emailSubject: emailSubject, CategoryID: Categorynode.id, EmailCompany: EmailCompany }
                        },
                        success: function (data) {
                            if (data == 1) {
                                $.messager.alert('Morgan CRM', 'Email template successfully added.');
                                cancelEmailTemplate();
                            }
                            else {
                                $.messager.alert('Morgan CRM', 'Email template already exist.');
                            }
                        }
                    });
                }

            }
        }
    }

    function openDelEmailPopup() {
        var row = $('#dgList').datagrid('getSelected');
        if (row) {
            $('#dlgDelList').dialog('open');

        }
    }
    //delete list data:
    function deleteEmailTemplate() {
        var row = $('#dgList').datagrid('getSelected');
        if (row) {
            $.ajax({
                url: '/WebServices/EmailTemplate.ashx',
                type: 'POST',
                data: {
                    method: 'DeleteListData',
                    args: { EmailId: row.EmailId }

                },
                success: function (data) {
                    $('#dgList').datagrid('reload');
                    $('#dlgDelList').dialog('close');
                }
            });
        }
    }
    $('#dlgETem').dialog({
        onOpen: function () {
            window.resizeTo(window.innerWidth + 25, window.innerHeight + 70);
            window.focus();

        },
        onClose: function () {
            window.resizeTo(698, 750);
            window.focus();
        }
    });
    //Adjust window on resize


    window.onresize = function () {

        $('#pnlMain').panel('resize', {
            width: window.innerWidth - 2,
            height: window.innerHeight - 2
        });

        $('#pnltree').panel('resize', {
            height: window.innerHeight - 35
        });

        $('#dgList').datagrid('resize', {
            width: window.innerWidth - 310,
            height: window.innerHeight - 35
        });


    }

    function editEmailTemplate() {
        var row = $('#dgList').datagrid('getSelected');
        if (row) {
            $('#dlgETem').dialog('open');
            $('#lnkNewEmailTemp').show();
            $('#txtEmailTemplate').hide();
            $('#spnddlEmailTemplate').show();
            $('#dlgETem').panel('setTitle', 'Edit E-Mail Template');



            var currentTemplateId = row.EmailId;

            if (currentTemplateId == -1) {
                $.messager.alert('Morgan CRM', 'Please select Template Item ... !', 'warning');
            }

            else {

                $.ajax({
                    url: "/WebServices/EmailTemplate.ashx?method=GetEmailTemplateContentById",
                    contentType: "application/json; charset=utf-8",
                    data: { EmailTemplateId: currentTemplateId },
                    success: function (data) {
                        $.each(eval(data.replace(/[\r\n]/, '')), function (i, result) {

                            $('#txtEmailSub').val(result.emailsubject);

                            $('#cmbCategory').combotree('setValue', result.CategoryId);

                            $('#ddlEMAILTemplate').combotree('setValue', row.EmailId);
                            tinymce.get('txtTemplate').setContent(decodeURIComponent(result.TemplateFormat));
                            var defEmailRole = result.EmailCompany;
                            if (defEmailRole != null) {
                                var setEmailRole = defEmailRole.split(',');
                                $('#cmbEmailRoles').combobox('setValues', setEmailRole);
                            }
                            else {
                                $('#cmbEmailRoles').combobox('setValues', '');
                            }
                        });
                    }

                });
            }
        }
    }



    //On select value:
    function selectEmailTemplate(node) {
        var currentTemplateId = node.id;
        if (currentTemplateId == -1) {
            $.messager.alert('Morgan CRM', 'Please select Template Item ... !', 'warning');
        }
        else {
            $('#lnkDeleteEmailTemp').show();
            $.ajax({
                url: "/WebServices/EmailTemplate.ashx?method=GetEmailTemplateContentById",
                contentType: "application/json; charset=utf-8",
                data: { EmailTemplateId: currentTemplateId },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, result) {

                        $('#txtEmailSub').val(result.emailsubject);
                        $('#cmbCategory').combotree('setValue', result.CategoryId);
                        tinymce.get('txtTemplate').setContent(decodeURIComponent(result.TemplateFormat));
                        var defEmailRole = result.EmailCompany;
                        if (defEmailRole != null) {
                            var setEmailRole = defEmailRole.split(',');
                            $('#cmbEmailRoles').combobox('setValues', setEmailRole);
                        }
                        else {
                            $('#cmbEmailRoles').combobox('setValues', '');
                        }
                    });
                }

            });
        }
    }



    //Load all list items:
    $(document).ready(function () {
        $('#pnlemail').dialog('close');
        $("#dgMainTbl").css("visibility", "visible");
        $('#dgList').datagrid({
            onDblClickRow: function (index, rowdata) {
                editEmailTemplate();
            },
        });
    });

</script>
</html>
